//定时任务
var scheduleJobGrid ;
$(function (){
	var grid = $('#scheduleJobGrid');
    var width = 200;
	PageLoader = {
	    initGridPanel: function(){
	         var self = this;
	         return grid.grid({
	                identity:"jobId",
	                buttons: [
	                        {content: '<button class="btn btn-primary" type="button"><span class="glyphicon glyphicon-plus"><span>添加</button>', action: 'add'},
	                        {content: '<button class="btn btn-success" type="button"><span class="glyphicon glyphicon-edit"><span>修改</button>', action: 'modify'},
	                        {content: '<button class="btn btn-success refresh" type="button" ><span class="glyphicon glyphicon-edit"><span>刷新</button>', action: 'refresh'}
	                ],
	                url:contextPath+"/scheduleJob/getPageData.dhc",
	                columns:  [
	  	                  	 { title: '任务名称', name: 'jobName', width: 150},
		                  	 { title: '执行时间', name: 'jobExecuteTime', width: 120},
		                  	 { title: '任务cron表达式', name: 'cronExpression', width: 100},
//		                 	 { title: '任务描述', name: 'description', width: 160},
		                 	 { title: '任务状态', name: 'jobStatus', width: 70, render: function (rowdata, name, index) {
		                 		 var show = '启用';
		                 		 if(rowdata && rowdata.jobStatus == '1'){
		                 			show = '<span style="color:#5cb85c;">启用</span>';
		                 		 }else{
		                 			show = '<span style="color: red;">禁用</span>';
		                 		 }
		                 		 return show ;
                         	 }},
		                 	 { title: 'bean的地址', name: 'beanClass', width: 220},
		                 	 { title: '执行方法', name: 'methodName', width: 170},
		                 	 { title: '方法参数', name: 'jobData', width: 100},
			                 { title: '操作', width: 100, render: function (rowdata, name, index)
			                     {
        					    	var  tdOperate = '';                            
                                    if(rowdata.jobStatus == '1'){
                                    	tdOperate += "<a href=\"javascript:pauseScheduleJob('"+rowdata.jobId+"')\"><span class=\"label label-danger\">禁用</span></a> ";
                                    }else{
                                    	tdOperate += "<a href=\"javascript:resumeScheduleJob('"+rowdata.jobId+"')\"><span class=\"label label-success\">启用</span></a> ";
                                    }
                                    tdOperate += "<a href=\"javascript:runOnceScheduleJob('"+rowdata.jobId+"')\"><span class=\"label label-primary\">立即执行</span></a> ";
							    	return tdOperate;
			                     }
			                 }
	        		 ]  
	         }).on({
	                   'add': function(){
	                       self.add($(this));
	                   },
	                   'modify': function(event, data){
	                	   var item = data.item;
	                        var indexs = data.data;
	                        var $this = $(this);
	                        if(indexs.length == 0){
	                            drgUI.error('请选择一条记录进行修改!');
	                            return;
	                        }
	                        if(indexs.length > 1){
	                            drgUI.warning('只能选择一条记录进行修改!');
	                            return;
	                        }
	                       self.modify(data.item[0],indexs[0], $this);
	                    },
	                    'refresh': function(){
		                    self.refresh($(this));
		                }
	         });
	         
	    },
	    add: function(grid){
	        var self = this;
	        var dialog = $('<div class="modal fade"><div class="modal-dialog">'
	        	+'<div class="modal-content"><div class="modal-header"><button type="button" class="close" '
	        	+'data-dismiss="modal" aria-hidden="true">&times;</button>'
	        	+'<h4 class="modal-title">新增</h4></div><div class="modal-body">'
	        	+'<p>One fine body&hellip;</p></div><div class="modal-footer">'
	        	+'<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>'
	        	+'<button type="button" class="btn btn-success" id="save">保存</button></div></div>'
	        	+'</div></div>') ;
	        
	        $.get(contextPath+"/pages/scheduleJob/scheduleJob-add.jsp").done(function(html){
	        	dialog.find(".modal-dialog").css('width','580');
	        	dialog.modal({
	                keyboard:false
	            }).on({
	                'hidden.bs.modal': function(){
	                    $(this).remove();
	                }
	            }).find('.modal-body').html(html);
		        dialog.find("#jobNameID").blur(function(){
		        	$("#jobGroupID").val($.trim($(this).val())+'组');
		        });
		    	//加载cron表达式
		        dialog.find('#selector').cron({
		    		onChange: function() {
		    			dialog.find('#cronExpressionID').val($(this).cron("value"));
		    		}
		    	}); 
		        
	        });

	        dialog.find('#save').on('click',{grid: grid}, function(e){
				var jobName = $.trim($("#jobNameID").val());
				var jobGroup = $.trim($("#jobGroupID").val());
				var description = $.trim($("#descriptionID").val());
				var beanClass = $.trim($("#beanClassID").val());
				var methodName = $.trim($("#methodNameID").val());
				var cronExpression = $.trim($("#cronExpressionID").val());
				var jobData = $.trim($("#jobDataID").val());
				var jobExecuteTime="";
				if(cronExpression && cronExpression.split(" ").length >= 6 ){
					var arr = cronExpression.split(" ");
					if(arr[4] != '*'){
						jobExecuteTime +="每年"+arr[4]+"月 ";
					}
					if(arr[5] != '*' && arr[5] != '?'){
						switch(arr[5])
						{
							case '0':
								jobExecuteTime +=" 每个星期天 ";
								arr[5] = '7';//修正插件里面 星期天的值为0的bug，值应该为7
							  break;
							case '1':
								jobExecuteTime +=" 每个星期一 ";
							  break;
							case '2':
								jobExecuteTime +=" 每个星期二 ";
							  break;
							case '3':
								jobExecuteTime +=" 每个星期三 ";
							  break;
							case '4':
								jobExecuteTime +=" 每个星期四 ";
							  break;
							case '5':
								jobExecuteTime +=" 每个星期五 ";
							  break;
							case '6':
								jobExecuteTime +=" 每个星期六 ";
							  break;
							case '7':
								jobExecuteTime +=" 每个星期天 ";
							  break;
							default:
								jobExecuteTime +=" 每个星期天 ";
								arr[5] = '7';
						}
					}
					if(arr[3] != '*' && arr[3] != '?'){
						jobExecuteTime ? (jobExecuteTime += arr[3]+"日 " ):( jobExecuteTime +="每月 "+arr[3]+"日 " );
					}
					if(arr[2] != '*' ){
						jobExecuteTime ? (jobExecuteTime += arr[2]+"时 " ):( jobExecuteTime +="每天 "+arr[2]+"时 " );
					}
					if(arr[1] != '*' ){
						jobExecuteTime ? (jobExecuteTime += arr[1]+"分 " ):( jobExecuteTime +="每小时 "+arr[1]+"分 " );
					}
					if(arr[0] != '*' ){
						jobExecuteTime ? (jobExecuteTime += arr[0]+"秒 " ):( jobExecuteTime +="每分钟 "+arr[0]+"秒 " );
					}
					cronExpression = arr.join(" ");
				}
				// 验证是否通过
				var flag = true ;
				dialog.find("input[datatype='Require']").each(function(index,element){
					if($(element).val()=="") {
						$(element).focus();
						drgUI.error('带*的为必填项!');
						flag = false ;
						return flag ;
					}
				})
				if(!flag) { //验证未通过
					return ;
				}
		        $.post(contextPath+"/scheduleJob/isExist.dhc",{"jobName":jobName}).done(function(result){
		        	  if(result.data) {
		        		  drgUI.error('任务名已存在，请重新输入!');
		        		  return ;
		        	  } else { 
		        		  var param = {"jobName":jobName,"jobGroup":jobGroup,"description":description,"beanClass":beanClass,
		        				  "methodName":methodName,"cronExpression":cronExpression,"jobData":jobData,"jobExecuteTime":jobExecuteTime} ;
		        		   console.log(param);
		        		  $.post(contextPath+"/scheduleJob/add.dhc", param).done(function(result){
		                   if(result.success ){
		                        dialog.modal('hide');
		                        e.data.grid.data('koala.grid').refresh();
		                        drgUI.success('保存成功!');
		                    }else{
		                     	drgUI.error(result.actionError);
		                     }
		                 });
		        	  }
		          });
		    });
		},
	    modify: function(item,id, grid) {
	        var self = this;
	        var cronflag=0;
	        var dialog = $('<div class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h4 class="modal-title">修改</h4></div><div class="modal-body"><p>One fine body&hellip;</p></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button><button type="button" class="btn btn-success" id="save">保存</button></div></div></div></div>');
	        $.get(contextPath+"/pages/scheduleJob/scheduleJob-update.jsp").done(function(html){
	               dialog.find('.modal-body').html(html);
	               dialog.find(".modal-dialog").css('width','580');
	               dialog.find('#jobNameID').val($.trim(item.jobName));
	               dialog.find('#jobGroupID').val($.trim(item.jobGroup));
	               dialog.find('#descriptionID').val($.trim(item.description));
	               dialog.find('#beanClassID').val($.trim(item.beanClass));
	               dialog.find('#methodNameID').val($.trim(item.methodName));
	               dialog.find("#cronExpressionID").val($.trim(item.cronExpression));
	               dialog.find("#jobDataID").val($.trim(item.jobData));
	               dialog.find("#jobStatusID").val($.trim(item.jobStatus));
	               dialog.find('#jobID').val(id);
	              
	               dialog.find('#jobNameID,#jobGroupID,#beanClassID,#methodNameID,#jobDataID').attr("disabled",true);

	               dialog.modal({
	                    keyboard:false
	               }).on({
	                    'hidden.bs.modal': function(){
	                        $(this).remove();
	                    }
	               });
			    	//加载cron表达式
			        var c = dialog.find('#selector').cron({
			    		onChange: function() {
			    			if(cronflag!=0){
				    			dialog.find('#cronExpressionID').val($(this).cron("value"));
			    			}
			    			cronflag++;
			    		}
			    	});	
			        
	   	        dialog.find('#save').on('click',{grid: grid}, function(e){
					var jobName = $("#jobNameID").val();
					var jobGroup = $("#jobGroupID").val();
					var description = $("#descriptionID").val();
					var beanClass = $("#beanClassID").val();
					var methodName = $("#methodNameID").val();
					var cronExpression = $("#cronExpressionID").val();
					var jobData = $("#jobDataID").val();
					var jobId = $("#jobID").val();
					var jobStatus = $("#jobStatusID").val();
					
					var jobExecuteTime="";
					if(cronExpression && cronExpression.split(" ").length >= 6 ){
						var arr = cronExpression.split(" ");
						if(arr[4] != '*'){
							jobExecuteTime +="每年"+arr[4]+"月 ";
						}
						if(arr[5] != '*' && arr[5] != '?'){
							switch(arr[5])
							{
								case '0':
									jobExecuteTime +=" 每个星期天 ";
									arr[5] = '7';//修正插件里面 星期天的值为0的bug，值应该为7
								  break;
								case '1':
									jobExecuteTime +=" 每个星期一 ";
								  break;
								case '2':
									jobExecuteTime +=" 每个星期二 ";
								  break;
								case '3':
									jobExecuteTime +=" 每个星期三 ";
								  break;
								case '4':
									jobExecuteTime +=" 每个星期四 ";
								  break;
								case '5':
									jobExecuteTime +=" 每个星期五 ";
								  break;
								case '6':
									jobExecuteTime +=" 每个星期六 ";
								  break;
								case '7':
									jobExecuteTime +=" 每个星期天 ";
								  break;
								default:
									jobExecuteTime +=" 每个星期天 ";
									arr[5] = '7';
							}
						}
						if(arr[3] != '*' && arr[3] != '?'){
							jobExecuteTime ? (jobExecuteTime += arr[3]+"日 " ):( jobExecuteTime +="每月 "+arr[3]+"日 " );
						}
						if(arr[2] != '*' ){
							jobExecuteTime ? (jobExecuteTime += arr[2]+"时 " ):( jobExecuteTime +="每天 "+arr[2]+"时 " );
						}
						if(arr[1] != '*' ){
							jobExecuteTime ? (jobExecuteTime += arr[1]+"分 " ):( jobExecuteTime +="每小时 "+arr[1]+"分 " );
						}
						if(arr[0] != '*' ){
							jobExecuteTime ? (jobExecuteTime += arr[0]+"秒 " ):( jobExecuteTime +="每分钟 "+arr[0]+"秒 " );
						}
						cronExpression = arr.join(" ");
					}
					
					// 验证是否通过
					var flag = true ;
					dialog.find("input[datatype='Require']").each(function(index,element){
						if($(element).val()=="") {
							$(element).focus();
							drgUI.error('带*的为必填项!');
							flag = false ;
							return flag ;
						}
					})
					if(!flag) { //验证未通过
						return ;
					}
	        		  var param = {"jobId":jobId,"jobName":jobName,"jobGroup":jobGroup,"description":description,"beanClass":beanClass,
	        				  "methodName":methodName,"cronExpression":cronExpression,"jobData":jobData,"jobExecuteTime":jobExecuteTime,"jobStatus":jobStatus} ;
	        		  $.post(contextPath+"/scheduleJob/update.dhc", param).done(function(result){
	                   if(result.success ){
	                        dialog.modal('hide');
	                        e.data.grid.data('koala.grid').refresh();
	                        drgUI.success('保存成功!');
	                    }else{
	                     	drgUI.error(result.actionError);
	                     }
	                 });
			    });
	        });
	    },
	    refresh: function(grid) {
	    	grid.data('koala.grid').refresh();
	    }
	}

	PageLoader.initGridPanel();

	$("#"+tabId+" #scheduleJobGrid button.refresh").hide();
});


//启用
var resumeScheduleJob = function(id){
    $.post(contextPath+"/scheduleJob/resume.dhc",{"jobId":id}).done(function(result){
  	  if(result.success) {
  		drgUI.success('启用成功!');
  		$("#"+tabId+" #scheduleJobGrid button.refresh").trigger("click");
  	  } else { 
  		drgUI.error(result.actionError);
  	  }
    });
}
//禁用
var pauseScheduleJob = function(id){
    $.post(contextPath+"/scheduleJob/pause.dhc",{"jobId":id}).done(function(result){
  	  if(result.success) {
  		drgUI.success('禁用成功!');
  		$("#"+tabId+" #scheduleJobGrid button.refresh").trigger("click");
  	  } else { 
  		drgUI.error(result.actionError);
  	  }
    });
}
//立即执行
var runOnceScheduleJob = function(id){
    $.post(contextPath+"/scheduleJob/runOnce.dhc",{"jobId":id}).done(function(result){
  	  if(result.success) {
  		drgUI.success('立即执行成功!');
  	  } else { 
  		drgUI.error(result.actionError);
  	  }
    });
}
